package cn.hx.fristgame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 游戏主窗口
 */

public class GameFrame extends JFrame {
    Image bg = gameUtil.getImage("images/bg.jpg"); //调用工具类指定图片路径并赋值给变量bg
    Image PlaneImg = gameUtil.getImage("images/plane.png");

    plane p = new plane(PlaneImg,constant.PLANE_X,constant.PLANE_Y);
    shell s = new shell();
    @Override
    public void paint(Graphics g) { //paint为画窗口的方法，自动调用，g相当于画笔
    g.drawImage(bg,0,0,null);   //调用画笔画出bg

    p.drawSelf(g);                  //画飞机
    s.draw(g);
    }
    //内部类可以直接调用外部方法
    class PaintThread extends Thread{
        @Override
        public void run() {
            while (true){
                repaint();  //重画窗口

                try {
                    Thread.sleep(constant.SLEEP);   //40ms暂停一次程序刷新率为25fps
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class KeyCtrl extends KeyAdapter{   //键盘适配器
        @Override
        public void keyPressed(KeyEvent e) {    //按下某个键时
            p.addDirection(e);
        }

        @Override
        public void keyReleased(KeyEvent e) {   //取消按下某个键时
            p.minusDirection(e);
        }
    }

    public void launchFrame(){      //初始化窗口
        this.setTitle("打飞机，我要打飞机"); //窗口标题
        this.setVisible(true);      //使得窗口为可见状态
        this.setSize(constant.GAME_WIDTH,constant.GAME_HEIGHT); //设置窗口大小
        this.setLocation(constant.LOCAL_X,constant.LOCAL_Y);  //设置窗口位置，参考坐标系，窗口左上角为原点
        this.addWindowListener(new WindowAdapter() { //添加点击x停止运行程序

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        addKeyListener(new KeyCtrl());  //键盘监听
        new PaintThread().start();  //启动重画窗口线程
    }

    public static void main(String[] args) {
        GameFrame f = new  GameFrame(); //创建窗口对象
        f.launchFrame();            //调用launchFrame方法
    }

}
